<script setup lang="ts">
import keywordEmitter from '@/common/mitt/keywrod'

const show = ref(false)
const inputRef = ref()
let timer = null
const keyList = ref(['非人哉', '不是人呐', '哈哈哈'])
const keyWord = ref('')
const place = ref('')

const handClick = (e: string) => {
  place.value = e
  if (timer) {
    clearTimer()
  }
  show.value = true
  nextTick(() => {
    inputRef.value.focus()
  })
}
const handBlur = () => {
  timer = setTimeout(() => {
    show.value = false
    clearTimer()
  }, 600)
}

const clearTimer = () => {
  if (timer) {
    clearTimeout(timer)
    timer = null
  }
}

const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    performSearch()
  }
}

const router = useRouter()
const route = useRoute()
const performSearch = () => {
  if (route.path === '/classify') {
    keywordEmitter.emit('searchText', toRaw(keyWord.value))
  } else {
    router.push({
      path: '/classify',
      query: {
        keyWord: keyWord.value
      }
    })
  }
}
</script>

<template>
  <div class="norem-search">
    <template v-if="show">
      <input
        v-model="keyWord"
        class="norem-my-input"
        ref="inputRef"
        type="text"
        :placeholder="place"
        @focus="clearTimer()"
        @blur="handBlur()"
        @keydown="handleKeydown"
      />
    </template>
    <template v-else>
      <n-carousel
        direction="vertical"
        dot-placement="right"
        autoplay
        :show-dots="false"
        :show-arrow="false"
        :interval="3000"
        class="norem-swiper"
      >
        <div
          v-for="item in keyList"
          :key="item"
          class="norem-place"
          @click="handClick(item)"
        >
          {{ item }}
        </div>
      </n-carousel>
    </template>

    <button><i class="esayIcon esayIcon-sousuo"></i></button>
  </div>
</template>

<style scoped lang="scss">
.norem-search {
  background-color: #f4f4f4;
  border-radius: 15px;
  height: 32px;
  transition: all 0.4s cubic-bezier(0.22, 0.58, 0.12, 0.98);
  padding: 0 10px;
  display: flex;
  align-items: center;
  .norem-my-input {
    height: 32px;
    background-color: initial;
    border: 0;
    margin: 0 8px;
    transition: all 0.2s cubic-bezier(0.22, 0.58, 0.12, 0.98);
    outline: none;
    width: 118px;
    font-size: 12px;

    &:focus {
      width: 170px;
    }

    &::-webkit-input-placeholder {
      color: #aaa;
    }
  }
  .norem-swiper {
    height: 32px;
    width: 118px;
    margin: 0 8px;

    .norem-place {
      line-height: 32px;
      font-size: 12px;
      color: #aaa;
      cursor: text;
    }
  }

  button {
    border: none;
    cursor: pointer;
    i {
      color: gray;
      font-size: 17px;
    }
  }
}
</style>
